package  
{
	import flash.events.Event;
	import org.flixel.*;
	import org.flixel.FlxCamera;
	import org.flixel.FlxGroup;
	import org.flixel.FlxTileblock;

	public class Level extends FlxGroup
	{
		private var _left:LevelSection;
		private var _right:LevelSection;
		private var _alpha:Number = 1;
		

		private var _camera:FlxCamera;
		public function Level(groundLevelY:int, camera:FlxCamera) 
		{
			_camera = camera;
			var groundHeight:int = FlxG.height - groundLevelY;
			
			_left = makeNewSection( -FlxG.width / 2, 0);
			_right = makeNewSection( (_left.x + _left.width), 0);
			
			this.add(_left);
			this.add(_right);
			
			updateBounds();
		}
		
		public function get alpha():Number
		{
			return _alpha;
		}
		
		public function set alpha(a:Number):void
		{
			_alpha = a;
			_left.alpha = _alpha;
			_right.alpha = _alpha;
		}
		
		private function makeNewSection(x:int, y:int):LevelSection
		{
			var section:LevelSection = new LevelSection(FlxG.width * 2, FlxG.height, x, y);
			return section;
		}
		
		private function updateBounds():void
		{
			_camera.setBounds( _left.x, 0, _left.width + _right.width, FlxG.height );
			FlxG.worldBounds.x = _left.x;
			FlxG.worldBounds.width = _left.width + _right.width;
		}
		
		public override function update():void
		{
			var quarterWidth:Number = _left.width / 4.0;
			if (_camera.scroll.x < _left.x + quarterWidth)
			{
				// move _groundRight to be groundLeft
				var newLeftX:int = _left.x - _right.width;
				this.remove(_right);
				_right = _left;
				_left = makeNewSection(newLeftX, 0);
				this.add(_left);
				
				//trace("left = " + _left.x + "..." + (_left.x + _left.width) + ", right = " + _right.x + "..." + (_right.x + _right.width));
				updateBounds();
			}
			else if (_camera.scroll.x > _right.x + quarterWidth)
			{
				// move _groundLeft to be groundRight
				var newRightX:int = _right.x + _right.width;
				this.remove(_left);
				_left = _right;
				_right = makeNewSection(newRightX, 0);
				this.add(_right);
				
				//trace("left = " + _left.x + "..." + (_left.x + _left.width) + ", right = " + _right.x + "..." + (_right.x + _right.width));
				updateBounds();
			}
			
		}
		
	}

}